package org.biao.aliyundns.service.imple;

import com.aliyun.alidns20150109.Client;
import com.aliyun.alidns20150109.models.*;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import lombok.extern.slf4j.Slf4j;
import org.biao.aliyundns.service.AliyunDNSService;
import org.springframework.stereotype.Service;


@Slf4j
@Service
public class AliyunDNSServiceImpl implements AliyunDNSService {

    private final Config config = new Config()
            // 必填，您的 AccessKey ID
            .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
            // 必填，您的 AccessKey Secret
            .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
            .setEndpoint("alidns.cn-hangzhou.aliyuncs.com");

    public DescribeDomainRecordsResponseBody.DescribeDomainRecordsResponseBodyDomainRecordsRecord describeDomainRecord() {
        DescribeDomainRecordsRequest describeDomainRecordsRequest = new DescribeDomainRecordsRequest()
                .setLang("en")
                .setDomainName("zenic.top")
                .setPageSize(1L)
                .setPageNumber(1L);

        try {
            DescribeDomainRecordsResponse describeDomainRecordsResponse = new Client(config).describeDomainRecordsWithOptions(describeDomainRecordsRequest, new RuntimeOptions());
            return describeDomainRecordsResponse.getBody().getDomainRecords().getRecord().get(0);
        } catch (TeaException error) {
            log.error(error.message, error);
            throw error;
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            log.error(error.message, error);
            throw error;
        }
    }

    @Override
    public void updateDomainRecord(String recordId, String value) {
        UpdateDomainRecordRequest request = new UpdateDomainRecordRequest()
                .setRecordId(recordId)
                .setRR("www")
                .setType("A")
                .setValue(value);

        try {
            UpdateDomainRecordResponse updateDomainRecordResponse = new Client(config).updateDomainRecord(request);
        } catch (TeaException error) {
            log.error(error.message, error);
            throw error;
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            log.error(error.message, error);
            throw error;
        }
    }
}
